package com.googlecode.wmlynar.gwtbeans.client.ui;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

import com.google.gwt.user.client.ui.ChangeListener;
import com.google.gwt.user.client.ui.Widget;
import com.googlecode.wmlynar.gwtbeans.client.beans.SourcesPropertyChangeEvents;

/**
 * Wrapper for TextBox class that posts property change events.
 * 
 * @author Wojciech Mlynarczyk (wmlynar@gmail.com)
 * 
 */
public class TextBox extends com.google.gwt.user.client.ui.TextBox implements
        SourcesPropertyChangeEvents {

    PropertyChangeSupport support = new PropertyChangeSupport(this);

    private boolean modifiedByUser;

    public TextBox() {
        super();
        addChangeListener(new ChangeListener() {
            public void onChange(final Widget arg0) {
                setModifiedByUser(true);
                support.firePropertyChange("text", null, getText());
            }
        });
    }

    public void setText(final String text) {
        final String old = getText();
        super.setText(text);
        support.firePropertyChange("text", old, text);
    }

    public void addPropertyChangeListener(final String propertyName,
            final PropertyChangeListener listener) {
        support.addPropertyChangeListener(propertyName, listener);
    }

    public void removePropertyChangeListener(final String propertyName,
            final PropertyChangeListener listener) {
        support.removePropertyChangeListener(propertyName, listener);
    }

    public void setModifiedByUser(final boolean modifiedByUser) {
        if (this.modifiedByUser != modifiedByUser) {
            support.firePropertyChange("modifiedByUser", this.modifiedByUser,
                    this.modifiedByUser = modifiedByUser);
        }
    }

    public boolean isModifiedByUser() {
        return modifiedByUser;
    }
}
